# -*- coding: UTF-8 -*-
# __author__ = '10459'
from flask import jsonify, request, render_template, flash
import json
from app.libs.helper import is_isbn_or_key
from app.models.gift import Gift
from app.models.wish import Wish
from app.spider.yushu_book import YuShuBook
from app.formsjiaoyan.book import SearchForm
from . import web
from app.view_models.book import BookViewModel, BookCollection
from app.view_models.trade import TradeInfo
from flask_login import current_user


# from . import 表示从当前路径导入
# 装饰器不能用import导入


@web.route('/book/search')
def search():
    forms = SearchForm(request.args)
    books = BookCollection()

    if forms.validate():
        q = forms.q.data.strip()
        page = forms.page.data
        isbn_or_key = is_isbn_or_key(q)
        yushu_book = YuShuBook()

        if isbn_or_key == 'isbn':
            yushu_book.search_by_isbn(q)
            # result = YuShuBook.search_by_isbn(q)
            # result = BookViewModel.package_single(result,q) #将服务器返回结果修改成统一格式

        else:
            yushu_book.search_by_keyword(q, page)

        books.fill(yushu_book, q)
        # python不能序列化对象，但是可以序列化字典，一般__dict__就可以，但是对象里面还有对象，就要特殊处理
        # 递归的序列化，所以一般用json，不用jsonfy
        # return json.dumps(books,default=lambda o:o.__dict__)

        # result = YuShuBook.search_by_keyword(q,page)
        # result = BookViewModel.package_collection(result,q)  #将服务器返回结果修改成统一格式
        # return jsonify(result)
    else:
        flash("你妹的，您的搜索不符合条件，请重试")
    return render_template("search_result.html", books=books, forms=forms)

    # return jsonify(forms.errors)
    # 第二种写法
    # return json.dumps(result),200,{'content-type':'application/json','charset':'utf-8'}


# web.route('/test')
# def test():
#     r = {
#         'name': None,
#         'age': 18
#     }
#     # data['age']
#     r1 = {
#
#     }
#     flash('hello,qiyue', category='error')
#     flash('hello, jiuyue', category='warning')
#     # 模板 html
#     return render_template('test.html', data=r, data1=r1)

@web.route('/book/<isbn>/detail')
def book_detail(isbn):
    has_in_gifts = False
    has_in_wishes = False
    # 取书籍详情数据
    yushu_book = YuShuBook()
    yushu_book.search_by_isbn(isbn)
    # book = BookViewModel(yushu_book.books[0])#这个写法不好
    book = BookViewModel(yushu_book.first)
    if current_user.is_authenticated:
        #在框架中改写了filter_by，加了status=1，重写基类方法，就是改基类方法
        if Gift.query.filter_by(uid=current_user.id,isbn=isbn,launched=False).first():
            has_in_gifts = True
        if Wish.query.filter_by(uid=current_user.id,isbn=isbn,launched=False).first():
            has_in_wishes = True

    trade_gifts = Gift.query.filter_by(isbn=isbn, launched=False).all()  # filter_by后面加.才会触发查询操作
    trade_wishes = Wish.query.filter_by(isbn=isbn, launched=False).all()
    trade_gifts_model = TradeInfo(trade_gifts)
    trade_wishes_model = TradeInfo(trade_wishes)
    return render_template("book_detail.html",
                           book=book, wishes=trade_wishes_model,
                           gifts=trade_gifts_model,
                           has_in_gifts=has_in_gifts,
                           has_in_wishes=has_in_wishes)


@web.route('/test')
def test():
    r = {
        "name": "七月",
        "age": 18,
        "school": "Qinghua"
    }
    r1 = {
        "name": 'louis',
        "age": 20
    }
    # 消息闪现，这个函数返回是元组
    flash("hello,Louis", category="error")
    flash("hello,qiyue", category="warning")
    # html模板,render_template导入模板
    # 不要太在意这个报错
    return render_template('test.html', data=r, data1=r1)
    #
    # @web.route('/test2')
    # def test2():
    #
    #     r = {
    #         "name":"七月",
    #         "age":18
    #         }
    #     r1={
    #         "name":'louis',
    #         "age":20
    #     }
    #     #html模板,render_template导入模板
    #     #不要太在意这个报错
    #     return render_template('test2.html',data=r,data1=r1)
